<template>
  <div class="Login">
    <Particles :backgroundImage="getImageUrl('images/login/login-bg.jpg')">
      <BorderBox11 title="大屏设计器" class="login-form-content animate__animated animate__bounceInDown">
        <div class="login-form">
          <el-form @submit.native.prevent size="large" ref="loginFormRef" :model="loginForm">
            <el-row>
              <el-col :span="24">
                <el-form-item prop="username" :rules="[{required: true, message: '请输入用户名', trigger: 'blur'}]">
                  <el-input prefix-icon="User" placeholder="请输入用户名" class="wft-w-100" v-model="loginForm.username" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item prop="password" :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }, { validator: isStrongPwdCallback, trigger: 'blur' }]">
                  <el-input type="password" prefix-icon="Lock" placeholder="请输入密码" class="wft-w-100" v-model="loginForm.password" />
                </el-form-item>
              </el-col>
              <el-col :span="18">
                <el-form-item prop="code" :rules="[{ validator: validateCode, trigger: 'blur' }]">
                  <el-input prefix-icon="Key" v-model="loginForm.code" placeholder="请输入验证码"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <div class="wft-w-h-100" style="cursor: pointer;" @click="changeCode">
                  <Sidentify :identifyCode="identifyCode" :isBgTransparent="true" :contentWidth="90" />
                </div>
              </el-col>
              <el-col :span="24">
                <el-form-item>
                  <el-button class="wft-w-100" :loading="loading" @click="login">登 录</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </BorderBox11>
    </Particles>
  </div>
</template>
<script setup lang='ts'>
import { getImageUrl } from '@/utils'
import { reactive, ref, defineAsyncComponent, onMounted, onUnmounted } from 'vue'
import { isStrongPwd } from 'wft-utils'
import type { FormInstance } from 'element-plus'
import { useRouter } from 'vue-router'
import { useMessage } from '@/hooks'
import { localCache } from '@/utils/storageCache'
import { LoginKeyEnum, KeyEventEnum } from '@/enums'

const Particles = defineAsyncComponent(() => import('@/components/Particles/index.vue'))
const Sidentify = defineAsyncComponent(() => import('@/components/Sidentify/index.vue'))

const router = useRouter()

const loginForm = reactive({
  username: 'admin',
  password: 'Aa!12345',
  code: 'm6a8'
})

const loginFormRef = ref<FormInstance>()
let loading = ref(false)
// 是随机生成的验证码
const identifyCode = ref('m6a8')
// 验证码的随机取值范围
const identifyCodes = '123456789abcdefghjkmnpqrstuvwxyz'

onMounted(() => {
  window.addEventListener(KeyEventEnum.ON_KEY_DOWN, keyDown)
})

onUnmounted(() => {
  window.removeEventListener(KeyEventEnum.ON_KEY_DOWN, keyDown)
})

const isStrongPwdCallback = (_rule: any, value: string, callback: (params?: any) => void) => {
  if (value && !isStrongPwd(value)) {
    callback(new Error('密码必须包含大写字母、小写字母、数字、特殊字符，长度8到16'))
  } else {
    callback()
  }
}

// 点击验证码触发
const changeCode = () => {
  identifyCode.value = ''
  makeCode(identifyCodes, 4)
}

// 随机生成验证码字符串
const makeCode = (data: string, len: number) => {
  for (let i = 0; i < len; i++) {
    identifyCode.value += data[randomNum(0, data.length - 1)]
  }
}

// 生成一个随机整数  randomNum(0, 10) 0 到 10 的随机整数， 包含 0 和 10
const randomNum = (min: number, max: number) => {
  max = max + 1
  return Math.floor(Math.random() * (max - min) + min)
}

// 验证码校验
const validateCode = (rule: any, value: string, callback: (params?: any) => void) => {
  rule = rule
  if (identifyCode.value !== value) {
    loginForm.code = ''
    changeCode()
    callback(new Error('请输入正确的验证码'))
  } else {
    callback()
  }
}

const login = () => {
  if(!loginFormRef.value) return
  loginFormRef.value?.validate((valid: boolean) => {
    if(valid) {
      loading.value = true
      setTimeout(() => {
        if(loginForm.username !== 'admin' || loginForm.password !== 'Aa!12345') {
          loading.value = false
          return useMessage().error('用户名或密码错误!')
        }
        localCache.setCache(LoginKeyEnum.SET_TOKEN_KEY, 'wft12345678987654321wftwft')
        router.replace('/')
        loading.value = false
      }, 500)
    }
  })
}

function keyDown(event: KeyboardEvent) {
  if(event.key === 'Enter') {
    login()
  }
}
</script>
<style scoped>
.Login {
  width: 100%;
  height: 100%;
}
.login-form-content {
  width: 100%;
  height: 100%;
}
.login-form {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding-top: 12%;
  box-sizing: border-box;
}

:deep(.el-form) {
  width: 80%;
}

/* 输入框 */
:deep(.el-input__wrapper) {
  background-color: transparent!important;
  transition: border-color .5s, box-shadow .5s!important;
  /* 去掉边框 目前只能通过设置box-shadow的方式 */
  border: 1px solid transparent!important;
  border-bottom-color: #455b87!important;
  box-shadow: 0 0 3px transparent!important;
}

:deep(.el-input__inner) {
  color: #fff!important;
}

:deep(.el-input__wrapper:hover),
:deep(.el-form-item.is-error .el-input__wrapper.is-focus) {
  border: 1px solid transparent!important;
  border-bottom-color: #8aaafb!important;
  box-shadow: 0 0 3px transparent!important;
}

:deep(.el-button) {
  background-color: rgba(10, 38, 84, .5)!important;
  color: #fff!important;
  border-color: rgba(10, 38, 84, .3)!important;
  transition: all .5s!important;
  transform: translateY(10px);
}
:deep(.el-button:hover) {
  color: #fff!important;
  border-color: rgba(10, 38, 84, .9)!important;
  background-color: rgba(10, 38, 84, .6)!important;
}
:deep(.el-button.is-disabled) {
  background-color: rgba(69, 88, 132, .5)!important;
  color: red!important;
  border-color: rgba(69, 88, 132, .7)!important;
}
</style>